/*
Copyright (c) 2008, Oleg S. Estekhin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of the copyright holders nor the names of its
      contributors may be used to endorse or promote products derived from this
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package ebml.viewer;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;
import java.util.prefs.Preferences;

import javax.swing.SwingUtilities;

import ebml.ElementDescriptor;
import ebml.ElementDescriptorProvider;
import ebml.ElementType;
import ebml.VInteger;
import ebml.viewer.table.ExtendedColumn;
import ebml.viewer.table.ExtendedTableModel;

/** Contains a list of known elements. */
public final class ElementListTableModel extends ExtendedTableModel {

    private static final ResourceBundle RESOURCES = ResourceBundle.getBundle(Resources.class.getName());

    private static final Preferences PREFERENCES = Preferences.userNodeForPackage(ElementListTableModel.class).node("loadContents");


    private static final ExtendedColumn[] COLUMNS = {
            new ExtendedColumn("table.elementList.identifier", VInteger.class, 75, new ElementIdentifierTableCellRenderer(), new ElementIdentifierComparator()),
            new ExtendedColumn("table.elementList.name", String.class, 100, null, null),
            new ExtendedColumn("table.elementList.type", ElementType.class, 100, new ElementTypeTableCellRenderer(), null),
            new ExtendedColumn("table.elementList.loadContents", Boolean.class, 25, null, null),
    };


    private final ElementDescriptorProvider descriptorProvider;

    private final List<Row> data;

    private final Map<VInteger, Boolean> loadContents;


    /**
     * Creates a new <code>ElementListTableModel</code> object.
     *
     * @param descriptorProvider the element descriptor provider
     *
     * @throws NullPointerException if <code>descriptorProvider</code> is <code>null</code>
     */
    public ElementListTableModel(ElementDescriptorProvider descriptorProvider) {
        super(COLUMNS);
        if (descriptorProvider == null) {
            throw new NullPointerException("provider is null");
        }
        this.descriptorProvider = descriptorProvider;
        data = new ArrayList<Row>();
        loadContents = new ConcurrentHashMap<VInteger, Boolean>();
        for (ElementDescriptor e : descriptorProvider) {
            boolean initialLoadContents = true;
            if (e.getType() == ElementType.CONTAINER) {
                initialLoadContents = PREFERENCES.getBoolean(Long.toHexString(e.getIdentifierValue()), true);
                loadContents.put(e.getIdentifier(), initialLoadContents);
            }
            data.add(new Row(e.getIdentifier(), e.getName(), e.getType(), initialLoadContents));
        }
    }


    @Override
    public int getRowCount() {
        return data.size();
    }

    @Override
    public String getColumnName(int columnIndex) {
        return RESOURCES.getString(getColumnIdentifier(columnIndex));
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Row row = data.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return row.identifier;
            case 1:
                return row.name;
            case 2:
                return row.type;
            case 3:
                return row.loadContents;
            default:
                throw new AssertionError(columnIndex);
        }
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        Row row = data.get(rowIndex);
        return row.type == ElementType.CONTAINER && columnIndex == 3;
    }

    @Override
    public void setValueAt(Object value, int rowIndex, int columnIndex) {
        Row row = data.get(rowIndex);
        if (row.type == ElementType.CONTAINER && columnIndex == 3) {
            row.loadContents = (Boolean) value;
            loadContents.put(row.identifier, (Boolean) value);
            PREFERENCES.putBoolean(Long.toHexString(row.identifier.getEncodedValue()), (Boolean) value);
            fireTableCellUpdated(rowIndex, columnIndex);
        }
    }


    /**
     * Returns <code>true</code> if the viewer should load the contents of the element with the specified identifier.
     *
     * @param identifier the element identifier
     *
     * @return <code>true</code> if the element contents should be loaded
     *
     * @throws NullPointerException if <code>identifier</code> is <code>null</code>
     */
    public boolean isLoadContents(VInteger identifier) {
        if (identifier == null) {
            throw new NullPointerException("identifier is null");
        }
        ElementDescriptor descriptor = descriptorProvider.getElementDescriptor(identifier);
        if (descriptor != null && descriptor.getType() == ElementType.CONTAINER) {
            Boolean value = loadContents.get(identifier);
            return value == null ? true : value;
        } else {
            return true;
        }
    }

    /**
     * Determines whether the viewer should load the contents of the element with the specified identifier.
     *
     * @param identifier the element identifier
     * @param value whether or not to load the element contents
     *
     * @throws NullPointerException if <code>identifier</code> is <code>null</code>
     */
    public void setLoadContents(final VInteger identifier, final boolean value) {
        if (identifier == null) {
            throw new NullPointerException("identifier is null");
        }
        ElementDescriptor descriptor = descriptorProvider.getElementDescriptor(identifier);
        if (descriptor != null && descriptor.getType() == ElementType.CONTAINER) {
            if (SwingUtilities.isEventDispatchThread()) {
                setLoadContentsUnsafe(identifier, value);
            } else {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        setLoadContentsUnsafe(identifier, value);
                    }
                });
            }
        }
    }

    private void setLoadContentsUnsafe(VInteger identifier, boolean value) {
        loadContents.put(identifier, value);
        PREFERENCES.putBoolean(Long.toHexString(identifier.getEncodedValue()), value);
        for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) {
            Row row = data.get(rowIndex);
            if (row.identifier.equals(identifier)) {
                row.loadContents = value;
                fireTableCellUpdated(rowIndex, 3);
                break;
            }
        }
    }


    private static final class Row {

        private final VInteger identifier;

        private final String name;

        private final ElementType type;

        private boolean loadContents;

        private Row(VInteger identifier, String name, ElementType type, boolean loadContents) {
            this.identifier = identifier;
            this.name = name;
            this.type = type;
            this.loadContents = loadContents;
        }

    }

}
